import React,{useEffect,useState} from 'react'
import axios from "axios"
import AddresAlert from '../../component/AddresAlert'
import AddresList from '../../component/AddresList'
function Public(props) {
  let [addres,setaddres]=useState([])
  let [visible,setvisible]=useState(false)
  let [item,setItem]=useState("")
  useEffect(()=>{
    axios.get("/addres").then((res)=>{
      setaddres(res.data)

    })

  },[])
  const open=()=>{
    setvisible(true)
  }
  const removeaddres=(id)=>{
  addres=  addres.filter((item,index)=>{
          return item.id!==id
    })
    setaddres(addres)



  }
 const editAddress=(values)=>{
   addres=addres.map((items)=>{
     if(items.id===item.id){
       items={
         ...items,
         ...values,
         city: values.citys&&values.citys[1].name,
           province: values.citys&&values.citys[0].name,
         area:values.citys&&values.citys[2].name,
       
       
       }

     }
     return items
   })
   setaddres([...addres])

  }
  
  const openAlter=(item)=>{
    
    setItem(item)

  }
  const onClose=()=>{
    setvisible(false)
  }
 
  const addAddress=(values)=>{
    addres.push({
      ...values,
        id: new Date()*1,
        isDefault:false,
        city: values.citys&&values.citys[1].name,
        province: values.citys&&values.citys[0].name,
        area: values.citys&&values.citys[2].name
    }
    )
    setaddres(addres)
  }
  const editDefault =(id)=>{
    addres=addres.map((items)=>{
      if(items.id===id){
       items.isDefault=!items.isDefault
      }else{
        items.isDefault=false

      }
      return items
    })
    setaddres([...addres])
  }
  const topbu=(index)=>{
  let newarr= addres.splice (index,1)
  console.log(newarr)
  addres.unshift(newarr[0])
  setaddres([...addres])

  }

 
 
  return (

    <div>
      <AddresList addres={addres} open={open} 
       removeaddres={removeaddres} 
      openAlter={openAlter} 
      editDefault={editDefault}
      topbu={topbu}>
  
      </AddresList>
      <AddresAlert
      visible={visible}
      onClose={onClose}
      addAddress={addAddress}
      item={item}
    
     
      
      ></AddresAlert>   
    </div>
  )
}

export default Public